/*
 * ImmediateCrypt
 * Copyright (C) 2012 Giacomo Drago
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 * 
 * http://giacomodrago.com/go/immediatecrypt
 * 
 */

package com.giacomodrago.utils.gui;

import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;

/*
 * Source:
 * http://helpdesk.objects.com.au/java/how-to-limit-number-of-characters-in-jtextfield
 */
@SuppressWarnings("serial")
public class FixedSizeDocument extends PlainDocument {

    private final int max;
    private final FixedSizeListener listener;

    public FixedSizeDocument(int max, FixedSizeListener listener) {
        this.max = max;
        this.listener = listener;
    }

    @Override
    public void insertString(int offs, String str, AttributeSet a)
            throws BadLocationException {
        
        // check string being inserted does not exceed max length

        boolean limitReached = false;
        
        if (getLength() + str.length() > max) {
            // If it does, then truncate it
            str = str.substring(0, max - getLength());
            limitReached = true;
        }
        super.insertString(offs, str, a);
        
        if (limitReached) {
            listener.limitReached(this);
        }
        
    }
    
}
